'use strict';

var constant = require('../../const');
var models = require('../../models');
var crypto = require('crypto');
var debug = require('debug');
var request = require('request');

var config = {
	"sign_type": "MD5",
	"alipay_gateway": "https://mapi.alipay.com/gateway.do?",
	"https_verify_url": "https://mapi.alipay.com/gateway.do?service=notify_verify&",
	"partner": "2088811117366572",
	"key": "iqy7npb2mh1m42pkzqthgclhk34jflmw",
	"notify_url": "http://www.pocketsweet.com/wap/pay/notify",
	// "return_url": "http://moliantest.avosapps.om/pay/return"
}

var defaultParams = {
	service: 'alipay.wap.create.direct.pay.by.user',
	partner: config.partner,
	'_input_charset': 'utf-8',
	//支付类型，必填，不能修改
	payment_type: '1',
	notify_url: config.notify_url,
	// return_url: config.return_url
};

//获取充值页面
function getPayIndex(req, res) {
	var molianId = req.query.molianId || "";
	res.render('alipay/index', {
		"molianId": molianId
	});
}

function pay(req, res) {
	var price = req.body.price;
	var molianId = parseInt(req.body.molianId);
	var query = new AV.Query(models.MLUser);
	query.equalTo("molianId", molianId);
	query.find({
		success: function(users) {
			if (users.length > 0) {
				var params = {
					//商户网站订单系统中唯一订单号，必填
					out_trade_no: _creatTradNo(),
					//订单名称，必填
					subject: molianId + " chongzhi",
					//卖家支付宝帐户，必填
					seller_id: "2394814529@qq.com",
					// 付款金额，必填
					total_fee: price,
					// 订单描述
					body: price + "yuan",
				};
				// var html = getDirectPayReqHtml(params, 'get');
				// console.log(html);
				// res.send(html);
				var url1 = "https://mapi.alipay.com/gateway.do?"
				var finalParams = JSON.parse(JSON.stringify(defaultParams));
				for (var k in params) {
					finalParams[k] = params[k];
				}
				var reqParams = buildRequestPara(finalParams);
				for (k in reqParams) {
					url1 += k + "=" + reqParams[k] + "&";
				}
				res.send({
					"code": 0,
					url: url1
				});
			} else {
				res.send({
					"code": 1,
					msg: "该用户不存在"
				});
			}
		},
		error: function(error) {
			res.send({
				"code": 1,
				msg: "该用户不存在"
			});
		}
	});


}

//生成订单号码
function _creatTradNo() {
	var time = _dataFomat(new Date());
	var num = Math.ceil(Math.random() * 99999999);
	return time + num;
}

function _dataFomat(date) {
	var fmt = "yyyyMMdd";
	var o = {
		"M+": date.getMonth() + 1, //月份 
		"d+": date.getDate(), //日 
		"h+": date.getHours(), //小时 
		"m+": date.getMinutes(), //分 
		"s+": date.getSeconds(), //秒 
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度 
		"S": date.getMilliseconds() //毫秒 
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

function notify(req, res) {
	var molianId = req.body.subject.split(" ")[0];
	var content = req.body.body;
	var sn = req.body.out_trade_no;
	var price = parseInt(req.body.price);
	verify(req.body, function(err, result) {
		if (result == true) {


			var query = new AV.Query(models.MLUser);
			query.equalTo("molianId", parseInt(molianId));
			query.find({
				success: function(users) {
					if (users.length > 0) {
						var user = users[0];
						var balance = user.get('balance');
						balance += price;
						user.set('balance', balance);
						user.save(null, {
							success: function() {
								var ConsumeRecord = models.MLConsumeRecord;
								var record = new ConsumeRecord();
								record.set('money', price);
								record.set('user', users[0]);
								record.set('remark', '充值' + content);
								record.set('sn', sn);
								record.set('type', constant.FINANCE_TYPE_RECHARGE);
								record.save(null, {
									success: function() {
										AV.Cloud.run('sendSysMsg', {
											"touserId": user.id,
											"type": 0,
											"msg": "恭喜您，充值成功！充值金额若有延迟到账，退出登陆再重新登陆即可。"
										}, {
											success: function(result) {
												res.send({
													"code": 0,
													"msg": "发送成功"
												});
											},
											error: function(error) {
												res.send({
													"code": 1,
													"msg": "发送失败"
												});
											}
										});
										//保存记录
										AV.Cloud.run("incomeRecord", {
											"userId": user.id,
											"price": price,
											"type": constant.INCOME_TYPE_RECHARGE
										});
									},
									error: function(record, error) {
										console.log(error)
									}
								});
							},
							error: function(user, error) {
								console.log(error);
							}
						});
					}
				},
				error: function(error) {
					console.log(error);
				}
			});
		}
		res.send("success");
	});
}

// 生成及时到账交易请求 html
function getDirectPayReqHtml(params, strMethod) {
	var finalParams = JSON.parse(JSON.stringify(defaultParams));
	for (var k in params) {
		finalParams[k] = params[k];
	}
	//debug('params: %j', finalParams);
	var result = '<form id="alipaysubmit" name="alipaysubmit"' +
		' action="' + config.alipay_gateway + '"' +
		' method="' + strMethod + '">';
	var reqParams = buildRequestPara(finalParams);
	console.log(reqParams);
	for (k in reqParams) {
		result += '<input type="hidden" name="' + k + '" value="' + reqParams[k] + '"/><br />';
	}
	//submit按钮控件请不要含有name属性
	result += '<script>document.forms["alipaysubmit"].submit();</script>';
	debug('generate request html:', result);
	return result;
};

// 验证消息是否是支付宝发出的合法消息
function verify(params, cb) {
	//判断responsetTxt是否为true
	//responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
	if (!params.notify_id) {
		debug('verify err: notify_id is null.');
		return cb(null, false);
	}
	verifyResponse(params.notify_id, function(err, result) {
		if (err || !result) {
			debug('verify err:', err || result);
			return cb(err, false);
		}
		//判断 verifySign 是否为true
		//如果不是true，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
		if (verifySign(params, params.sign || '')) {
			return cb(null, true);
		}
		return cb(null, false);
	});
};

// 获取远程服务器ATN结果,验证返回URL
var verifyResponse = function(notifyId, cb) {
	var verifyUrl = config.https_verify_url + 'partner=' + config.partner + "&notify_id=" + notifyId;
	debug(verifyUrl);
	request(verifyUrl, function(err, res, body) {
		if (err) {
			return cb(err, false);
		}
		if (res.statusCode != 200) {
			debug('verify err:', body);
			return cb(null, false);
		}
		debug('verify result:', body);
		cb(null, body === 'true');
	});
};

var verifySign = function(params, sign) {
	if (config.sign_type === 'MD5') {
		var paramsStr = createLinkString(paraFilter(params));
		var mySign = crypto.createHash('md5').update(paramsStr + config.key).digest('hex');
		return sign == mySign;
	}
	return false;
};

var buildRequestPara = function(params) {
	var reqParams = paraFilter(params);
	var paramsStr = createLinkString(reqParams);
	if (config.sign_type === 'MD5') {
		reqParams.sign = crypto.createHash('md5').update(paramsStr + config.key).digest('hex');
		//debug('build request params: paramsString=' + paramsStr + ', sign=' + reqParams.sign);
		reqParams.sign_type = config.sign_type;
	} else {
		reqParams.sign = '';
	}
	return reqParams;
};

// 除去数组中的空值和签名参数
var paraFilter = function(params) {
	var result = {};
	if (!params) {
		return result;
	}
	for (var k in params) {
		if (!params[k] || params[k] === '' || k === 'sign' || k === 'sign_type') {
			continue;
		}
		result[k] = params[k];
	}
	return result;
};

// 将所有参数按照“参数=参数值”的模式用“&”字符拼接成字符串
var createLinkString = function(params) {
	var result = '';
	var sortKeys = Object.keys(params).sort();
	for (var i in sortKeys) {
		result += sortKeys[i] + '=' + params[sortKeys[i]] + '&';
	}
	if (result.length > 0) {
		return result.slice(0, -1);
	} else {
		return result.toString("utf-8");
	}
};

exports.getPayIndex = getPayIndex;
exports.pay = pay;
exports.notify = notify;